#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010,SC3036,SC3015 source=/dev/null
#
# Startup script to check for a factory reset
#

# function to check if a factory reset (clearing whole /usr/local) should be performed
# in addition we also resize /usr/local in case it hasn't been resized to SD card
# boundaries
check_factory_reset() {

  # only continue if .doFactoryReset file exists
  if [[ ! -r /usr/local/.doFactoryReset ]]; then
    return 1
  fi

  # source all data from /var/hm_mode
  [[ -r /var/hm_mode ]] && . /var/hm_mode

  if [[ ! "${HM_HOST}" =~ oci\|lxc ]]; then
    # extract device name and dev
    DEVNODE=$(mountpoint -d /usr/local)
    DEVNAME=$(mountpoint -n /usr/local | cut -d' ' -f1)
    DEV="/dev/$(readlink "/sys/dev/block/${DEVNODE}" | awk -F/ '{print $(NF-1)}')"

    # umount /usr/local to regenerate it
    umount -f /usr/local

    # force PARTUUID to 0xDEEDBEEF because due to some tools the
    # correct partuuid might have been lost
    PARTUUID=$(/sbin/blkid -o export "${DEVNAME}" | grep -m1 PARTUUID | cut -d= -f2)
    if [[ "${PARTUUID}" != "deedbeef-03" ]]; then
      echo -en '\xEF\xBE\xED\xDE' | dd of="${DEV}" conv=notrunc bs=1 seek=$((0x1B8)) 2>/dev/null
    fi

    # we create a clean ext4 partition now
    /sbin/mkfs.ext4 -F -L userfs -I 256 -E lazy_itable_init=0,lazy_journal_init=0 "${DEVNAME}"
    /sbin/tune2fs -c 0 -i 0 "${DEVNAME}"
    /sbin/e2fsck -pDf "${DEVNAME}"

    # mount /usr/local again
    mount /usr/local
  else
    # clean whole /usr/local on oci platform (usually a volume so cannot delete folder)
    find /usr/local -not -name "lost+found" -mindepth 1 -maxdepth 1 -exec rm -rf {} \;
  fi

  # make sure a potential rf copro is factory
  # reset as well
  touch /usr/local/.doCoproFactoryReset

  return 0
}

start() {
  echo -n "Checking for Factory Reset: "

  if check_factory_reset; then
    echo "cleared, OK"
  else
    echo "not required"
  fi
}

restart() {
  start
}

case "$1" in
  start)
    start
  ;;
  stop)
    # nothing
  ;;
  restart|reload)
    restart
  ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac

exit 0
